﻿using System;
using System.Linq;
using System.Web.Mvc;
using web.core.Models;
using web.core.ViewModels;
using web.component;
using web.data.entities;
using System.Collections.Generic;
using System.Web;

namespace web.core.Controllers
{
    public class CheckoutController : baseController
    {
        //const string PromoCode = "FREE";
        public ActionResult order_login()
        {
            if (Session["member_id"] != null)
            {
                return Redirect("/thong_tin_don_hang.ub");
            }
            else {
                Session["next_action"] = "/thong_tin_don_hang.ub";
                return PartialView("../checkout/order_login");
            }
            
        }

        public ActionResult payment_method()
        {
            IsMember();
            return PartialView("../checkout/payment_method");
        }

        public ActionResult member_order()
        {
            string test = this.Url.ToString();
            Session["next_action"] = "/phuong_thuc_thanh_toan.ub";
            //IsMember();
            return PartialView("../checkout/member_order");
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult create_order()
        {
            var order_view = new ViewModels.AddOrderViewModels();
            order_view.total = 0;
            System.Collections.Generic.List<SelectListItem> list_menthod = new System.Collections.Generic.List<SelectListItem>();

            if (Session["member_id"] != null)
            {
                order_view.user_id = int.Parse(Session["member_id"].ToString());
                var customer = checkoutModels.GetCustomerByUserID(int.Parse(Session["member_id"].ToString()));
                if (customer != null)
                {
                    order_view.customer_id = customer.customer_id;
                    order_view.full_name = customer.full_name;
                    order_view.email = customer.email;
                    order_view.address = customer.address;
                    order_view.mobile = customer.mobile;
                }
                order_view.label_form = "Vui lòng điền thông tin đơn hàng vào form dưới đây.";

                //list_menthod.AddRange(new SelectListItem[] { 
                //    new SelectListItem{Selected=true,Text = "Thanh toán tại địa chỉ nhận hàng", Value = Ustring.GetEnumIdToString(global_const.E_PAYMENT_TYPE.pay_at_address) },
                //    new SelectListItem{Selected=false,Text = "Thanh toán tại ubuy.vn", Value = Ustring.GetEnumIdToString(global_const.E_PAYMENT_TYPE.pay_at_ubuy) }
                //});
                //order_view.list_menthod = list_menthod;
            }
            else {
                order_view.label_form = "Hoặc điền thông tin đơn hàng vào form sau.";
            }
            return PartialView("../Shared/checkout/create_order", order_view);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult create_order(FormCollection values)
        {
            int new_id = 0;
            int cus_id = 0;
            int order_id = 0;
            string cus_pass = "";
            
            web.component.email_component email_com = new email_component();
            var order_view = new ViewModels.AddOrderViewModels();
            TryUpdateModel(order_view);

            //valid form in server code
            if (string.IsNullOrEmpty(order_view.full_name))
            {
                ViewBag.result_message = "Quý khách vui lòng điền Họ và Tên.";
                ViewBag.result = false;
                return PartialView("../Shared/checkout/create_order", order_view);
            }

            if (string.IsNullOrEmpty(order_view.address))
            {
                ViewBag.result_message = "Quý khách vui lòng nhập địa chỉ.";
                ViewBag.result = false;
                return PartialView("../Shared/checkout/create_order", order_view);
            }

            if (string.IsNullOrEmpty(order_view.email))
            {
                ViewBag.result_message = "Quý khách vui lòng nhập email.";
                ViewBag.result = false;
                return PartialView("../Shared/checkout/create_order", order_view);
            }

            if (string.IsNullOrEmpty(order_view.mobile))
            {
                ViewBag.result_message = "Quý khách vui lòng nhập số điện thoại có giá trị.";
                ViewBag.result = false;
                return PartialView("../Shared/checkout/create_order", order_view);
            }

            //check captcha text
            if (HttpContext.Session["captchastring"]!=null && order_view.captcha_text != HttpContext.Session["captchastring"].ToString())
            {
                ViewBag.result_message = "Quý khách vui lòng nhập lại mã xác nhận.";
                ViewBag.result = false;
                return PartialView("../Shared/checkout/create_order", order_view);
            }

            if (Session["member_id"] == null)
            {
                if (!string.IsNullOrEmpty(order_view.email) && !accountModels.CheckEmailExists(order_view.email))
                {
                    ViewBag.result_message = "Email này đã được sử dụng.";
                    ViewBag.result = false;
                    return PartialView("../Shared/checkout/create_order", order_view);
                }
            }

            

            if (order_view.user_id != null && order_view.user_id != 0 && Session["member_id"]!=null)
            {
                //neu da login thi chi tao order
                //get user and customer for user
                var user = accountModels.getUserByID(int.Parse(Session["member_id"].ToString()));
                if (user != null)
                {
                    var customer = checkoutModels.GetCustomerByUserID(user.user_id);
                    if (customer != null)
                    {
                        cus_id = customer.customer_id;
                    }
                }
            }
            else 
            { 
                //neu chua login thi tao account cho member vao tao order
                //create new user 
                web.component.Ustring ustr=new Ustring();
                cus_pass = ustr.RandomString(6, false);

                cryptography_component cryCom = new cryptography_component();
                string _password = cryCom.MD5(cus_pass);
                string _salt = _password.Substring(0, 5);
                string _cryptography_password = System.Configuration.ConfigurationManager.AppSettings["CryptographyPassword"].ToString();
                string _initial_vector = System.Configuration.ConfigurationManager.AppSettings["InitialVector"].ToString();
                string pass = cryCom.Encrypt(_password, _cryptography_password, _salt, _initial_vector);

                web.data.entities.users user = new data.entities.users();
                user.username = order_view.email;
                user.user_status = 1;
                user.email = order_view.email;
                user.created_date = web.component.Udate_time.GetCurrentDateTime();
                user.password = pass;
                user.salt = _salt;
                user.activation_code = web.component.global_const.ACTIVE_CODE_VANGLAI;
                user.active_date = web.component.Udate_time.GetCurrentDateTime();

                new_id = accountModels.createUser(user);

                if (new_id > 0)
                {
                    //add group for user
                    accountModels.addGroupForUser(web.component.global_const.GOURP_CUSTOMER, new_id);           //2 is customer group

                    //add new customer
                    web.data.entities.customer cus = new data.entities.customer()
                    {
                        full_name = order_view.full_name,
                        mobile = order_view.mobile,
                        email = order_view.email,
                        created_date =  web.component.Udate_time.GetCurrentDateTime(),
                        address = order_view.address,
                        status = true,
                        user_id = new_id
                    };
                    cus_id = accountModels.createCustomer(cus);
                }
                                
            }

            if ((order_view.user_id > 0 && cus_id > 0) || (new_id > 0 && cus_id > 0))
            {
                var cart = ShoppingCart.GetCart(this.HttpContext);
                //kiem tra gio hang co the pay online hay ko
                //is_pay = true khi tat ca cac san pham trong cart deu co gia  > 0
                var is_p = true;
                foreach (var item in cart.GetListCartItemByCartID())
                {
                    var _product = web.core.Models.productModels.GetProductViewByID(item.product_id ?? 0, Request.Url.PathAndQuery);
                    if (_product.price == null || _product.price <= 0)
                    {
                        is_p = false;
                    }
                }

                //create order
                web.data.entities.order oders = new order()
                {
                    order_date = web.component.Udate_time.GetCurrentDateTime(),
                    customer_id = cus_id,
                    full_name = order_view.full_name,
                    address = order_view.address,
                    phone = order_view.phone,
                    mobile = order_view.mobile,
                    email = order_view.email,
                    district = order_view.district,
                    city = order_view.city,
                    total = cart.GetTotalValueCartItem(),
                    created_date = web.component.Udate_time.GetCurrentDateTime(),
                    payment_status = 0,
                    user_id = new_id > 0 ?new_id:order_view.user_id,
                    is_pay = is_p
                };
                //list order detail
                System.Collections.Generic.List<order_detail> list_order_detail = new System.Collections.Generic.List<order_detail>();
                var list = cart.GetListCartItemByCartID();
                for(int i=0;i<list.Count;i++)
                {
                    var _product = web.core.Models.productModels.GetProductViewByID(list[i].product_id ?? 0, Request.Url.PathAndQuery);
                    web.data.entities.order_detail detail = new order_detail(){
                      product_id = list[i].product_id,
                      quantity = list[i].count,
                      price_value = (_product.price??0) * list[i].count
                    };
                    list_order_detail.Add(detail);
                }


                order_id = checkoutModels.createOrder(oders, list_order_detail);
                
            }

            if (order_id > 0)
            {
                //gui email toi khach hang va manager 
                if (new_id > 0)
                {
                    //email new account
                    var mail_id = global_const.EMAIL_ID_NEW_ACCOUNT;
                    var lst_content = new List<EmailVariable>()
                                  {
                                      new EmailVariable("client_name",order_view.full_name),
                                      new EmailVariable("password", cus_pass),
                                      new EmailVariable("email_login",order_view.email)
                                  };

                    var check_send_email_password = SendWebEmail(mail_id, lst_content, order_view.email, "", "");
                }
                
                //get content email for order
                var str_html_content = "<table style=\"width:100%; border-collapse:collapse;\"><tr><th style=\"width:20px;font-weight:bold; background:#EFEFEF;\">#</th>";
				str_html_content = str_html_content + "<th style=\"font-weight:bold; background:#EFEFEF;\">Sản phẩm</th><th style=\"width:120px;font-weight:bold; background:#EFEFEF;\">Giá</th></tr>";
                var cart = ShoppingCart.GetCart(this.HttpContext);
                var list = cart.GetListCartItemByCartID();
                var cartTotal = cart.GetTotalValueCartItem();
                for (int i = 0; i < list.Count; i++ )
                {
                    var _product = web.core.Models.productModels.GetProductViewByID(list[i].product_id ?? 0,Request.Url.PathAndQuery);
                    if (_product != null) {
                        str_html_content = str_html_content + "<tr>";
                        str_html_content = str_html_content + "<td style=\"border: solid 1px #E3E3E3; padding:5px;\">" + (i + 1) + "</td>";
                        str_html_content = str_html_content + "<td style=\"border: solid 1px #E3E3E3; padding:5px;\">" + Ucommon.GetDefaultString(_product.product_name, "") + "</td>";
                        str_html_content = str_html_content + "<td style=\"border: solid 1px #E3E3E3; padding:5px;\">" + Ustring.GetMoney2(_product.price??0) + "</td>";
                        str_html_content = str_html_content + "</tr>";
                    }
                    
                }
                str_html_content = str_html_content + "<tr>";
				str_html_content = str_html_content + "<td colspan=\"2\" align=\"right\" style=\"font-weight:bold; background:#EFEFEF;\">Tổng số:</td>";
				str_html_content = str_html_content + "<td style=\"font-weight:bold; background:#EFEFEF;\">"+Ustring.GetMoney2(cartTotal)+"</td>";
				str_html_content = str_html_content + "</tr>";
                str_html_content = str_html_content + "</table>";
                string lang_code = DefaultLanguageGetter();
                var email_admin = Uconfig.GetConfig(global_const.EMAIL, lang_code);
                var mail_order_id = global_const.EMAIL_ID_ORDER;
                var lst_order_content = new List<EmailVariable>()
                                  {
                                      new EmailVariable("client_name",order_view.full_name),
                                      new EmailVariable("client_email",order_view.email),
                                      new EmailVariable("client_phone",order_view.mobile),
                                      new EmailVariable("client_address",order_view.address),
                                      new EmailVariable("comment",order_view.comment),
                                      new EmailVariable("sent_date",DateTime.Now.ToString()),
                                      new EmailVariable("table_detail",str_html_content)
                                  };

                

                if (new_id > 0)
                {
                    //login cho user vua tao
                    Session["member_id"] = new_id;
                    HttpCookie ck = new HttpCookie("Sercurity_User");
                    ck.Values["username"] = order_view.email;
                    ck.Values["password"] = cus_pass;
                    ck.Values["user_id"] = new_id.ToString();
                    ck.Values["remember"] = "true";
                    ck.Expires = DateTime.Now.AddDays(1);//Thoi han luu cookie
                    HttpContext.Response.Cookies.Add(ck);
                }

                var check_send_email_order = SendWebEmail(mail_order_id, lst_order_content, order_view.email, email_admin, "");



                //chuyen den trang chon phuong thuc thanh toan
                ViewBag.result_message = "Tạo đơn hàng thành công.";
                ViewBag.result = true;
                Session["next_action"] = "/phuong_thuc_thanh_toan.ub";        //chon phuong thuc thanh toan
                ViewBag.redirect = Session["next_action"].ToString();
                return PartialView("../Shared/control_redirect");
            }
            else
            {
                ViewBag.result_message = "Tạo đơn hàng không thành công, vui lòng thử lại sau.";
                ViewBag.result = false;
                return PartialView("../Shared/checkout/create_order", order_view);
            }
        }

        /// <summary>
        /// Get metadata for order
        /// </summary>
        /// <param name="cateId"></param>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult order_metadata()
        {
            var metadata_view = new ViewModels.MetadataViewModels();

                metadata_view.title = "Thông tin đơn hàng";
                metadata_view.keyword = "";
                metadata_view.description = "";

            base_metadata(metadata_view);
            return PartialView("../Shared/commont/metadata");
        }

        [ChildActionOnly]
        [HttpGet]
        public ActionResult control_payment_menthod()
        {
            var menthod_view = new ViewModels.PaymentMethodViewModels();

            System.Collections.Generic.List<SelectListItem> list_menthod = new System.Collections.Generic.List<SelectListItem>();
            

            if (Session["member_id"] != null)
            {
                menthod_view.user_id = int.Parse(Session["member_id"].ToString());
                var order_pending = checkoutModels.GetLastOrderPendingByUserID(int.Parse(Session["member_id"].ToString()));
                if (order_pending != null)
                {
                    ////comment khi co pay online
                    //if (order_pending.is_pay != null && order_pending.is_pay == true)
                    //{
                    //    list_menthod.AddRange(new SelectListItem[] { 
                    //        new SelectListItem{Selected=true,Text = "Thanh toán tại địa chỉ nhận hàng", Value = Ustring.GetEnumIdToString(global_const.E_PAYMENT_TYPE.pay_at_address) },
                    //        new SelectListItem{Selected=false,Text = "Thanh toán tại ubuy.vn", Value = Ustring.GetEnumIdToString(global_const.E_PAYMENT_TYPE.pay_at_ubuy) },
                    //        new SelectListItem{Selected=false,Text = "Thanh toán paypal", Value = Ustring.GetEnumIdToString(global_const.E_PAYMENT_TYPE.pay_paypal) },
                    //        new SelectListItem{Selected=false,Text = "Thanh toán visa", Value = Ustring.GetEnumIdToString(global_const.E_PAYMENT_TYPE.pay_visa) }
                    //    });

                    //    menthod_view.label_form = "Tiếp theo";
                    //}
                    //else
                    //{
                    //    list_menthod.AddRange(new SelectListItem[] { 
                    //        new SelectListItem{Selected=true,Text = "Thanh toán tại địa chỉ nhận hàng", Value = Ustring.GetEnumIdToString(global_const.E_PAYMENT_TYPE.pay_at_address) },
                    //        new SelectListItem{Selected=false,Text = "Thanh toán tại ubuy.vn", Value = Ustring.GetEnumIdToString(global_const.E_PAYMENT_TYPE.pay_at_ubuy) }
                    //    });

                    //    menthod_view.label_form = "Hoàn tất";
                    //}

                    list_menthod.AddRange(new SelectListItem[] { 
                            new SelectListItem{Selected=true,Text = "Thanh toán tại địa chỉ nhận hàng", Value = Ustring.GetEnumIdToString(global_const.E_PAYMENT_TYPE.pay_at_address) },
                            new SelectListItem{Selected=false,Text = "Thanh toán tại ubuy.vn", Value = Ustring.GetEnumIdToString(global_const.E_PAYMENT_TYPE.pay_at_ubuy) }
                        });

                    menthod_view.label_form = "Hoàn tất";

                    menthod_view.customer_id = order_pending.customer_id;
                    menthod_view.full_name = order_pending.full_name;
                    menthod_view.email = order_pending.email;
                    menthod_view.address = order_pending.address;
                    menthod_view.mobile = order_pending.mobile;
                    menthod_view.list_menthod = list_menthod;
                    menthod_view.order_id = order_pending.order_id;
                }
            }
           
            return PartialView("../Shared/checkout/control_payment_menthod", menthod_view);
        }

        [ChildActionOnly]
        [HttpPost]
        public ActionResult control_payment_menthod(FormCollection values)
        {
            var menthod_view = new ViewModels.PaymentMethodViewModels();
            TryUpdateModel(menthod_view);

            if (!string.IsNullOrEmpty(menthod_view.menthod))
            {
                //update payment menthod 
                var order = checkoutModels.GetOrderByID(menthod_view.order_id ?? 0);
                if (order != null)
                {
                    order.payment_type = int.Parse(menthod_view.menthod);
                    checkoutModels.UpdatePaymentMenthodForOrder(order);
                }

                //xoa trang gio hang
                var cart = ShoppingCart.GetCart(this.HttpContext);
                var list = cart.GetListCartItemByCartID();
                ShoppingCart shopcart = new ShoppingCart();
                foreach (var item in list)
                {
                    shopcart.DeleteCartItem(item);
                }

                ViewBag.redirect = "/dat_hang_thanh_cong.ub";
                return PartialView("../Shared/control_redirect");
            }
            else {
                System.Collections.Generic.List<SelectListItem> list_menthod = new System.Collections.Generic.List<SelectListItem>();
                list_menthod.AddRange(new SelectListItem[] { 
                    new SelectListItem{Selected=true,Text = "Thanh toán tại địa chỉ nhận hàng", Value = Ustring.GetEnumIdToString(global_const.E_PAYMENT_TYPE.pay_at_address) },
                    new SelectListItem{Selected=false,Text = "Thanh toán tại ubuy.vn", Value = Ustring.GetEnumIdToString(global_const.E_PAYMENT_TYPE.pay_at_ubuy) }
                });
                menthod_view.list_menthod = list_menthod;
                ViewBag.result_message = "Xin vui lòng chọn phương thức thanh toán của bạn.";
                ViewBag.result = false;
                return PartialView("../Shared/checkout/control_payment_menthod", menthod_view);
            }
            
        }

        public ActionResult check_out_success() 
        {
            IsMember();
            var str_order_code = Uconfig.GetConfig(global_const.ORDER_CODE, global_const.LANGUAGE_CODE_DEFAULT);
            if (Session["member_id"] != null)
            {
                var order_pending = checkoutModels.GetLastOrderPendingByUserID(int.Parse(Session["member_id"].ToString()));
                if (order_pending != null)
                {
                    ViewData["ordername"] = order_pending.full_name;
                    ViewData["ordercode"] = str_order_code + order_pending.order_id ;
                }
            }
            return PartialView("../checkout/check_out_success");
        }

        //
        // POST: /Checkout/AddressAndPayment

        //[HttpPost]
        //public ActionResult AddressAndPayment(FormCollection values)
        //{
        //    var order = new Order();
        //    TryUpdateModel(order);

        //    try
        //    {
        //        if (string.Equals(values["PromoCode"], PromoCode,
        //            StringComparison.OrdinalIgnoreCase) == false)
        //        {
        //            return View(order);
        //        }
        //        else
        //        {
        //            order.Username = User.Identity.Name;
        //            order.OrderDate = DateTime.Now;

        //            //Save Order
        //            storeDB.Orders.Add(order);
        //            storeDB.SaveChanges();

        //            //Process the order
        //            var cart = ShoppingCart.GetCart(this.HttpContext);
        //            cart.CreateOrder(order);

        //            return RedirectToAction("Complete",
        //                new { id = order.OrderId });
        //        }

        //    }
        //    catch
        //    {
        //        //Invalid - redisplay with errors
        //        return View(order);
        //    }
        //}

        //
        // GET: /Checkout/Complete

        //public ActionResult Complete(int id)
        //{
        //    // Validate customer owns this order
        //    bool isValid = storeDB.Orders.Any(
        //        o => o.OrderId == id &&
        //        o.Username == User.Identity.Name);

        //    if (isValid)
        //    {
        //        return View(id);
        //    }
        //    else
        //    {
        //        return View("Error");
        //    }
        //}
    }
}
